<?php
   // This script outputs XML.
   header("Content-Type: text/xml;charset=UTF-8");
   echo '<?xml version="1.0"?>';
   echo "\n";
   // Need to have an argument named "id" set.
   if (!isset($_GET['id'])) {
      echo '<response><error>2</error><message>Plase specify ?id= when querrying this file.</message></response>';
      exit;
   }
   // Load the XML 'database' file books.xml into $xml.
   $xml = simplexml_load_file("books.xml");

   /*
   <books><floor>
   <book id="19">
      <range>
         <start>792.7</start> 
         <end>808.8</end> 
         <aisle>19</aisle>
      </range>
   </book>
    */
   $id = strtoupper(str_replace(" ", "", $_GET['id']));
   $count_floor = sizeof($xml->floor);

   // Search through all the book(s) to find the one which has the attribute "id" set to the desired value.
   for ($k=0; $k < $count_floor; $k++) {
      $floor = $xml->floor[$k]->attributes()->id;
      $count_book = sizeof($xml->floor[$k]->book);
      //echo $count_book;

      for ($i=0; $i < $count_book; $i++) {

         //$id = $xml->floor[$k]->book[$i]->attributes()->id;
         $start = strtoupper($xml->floor[$k]->book[$i]->range->start);
         $end = strtoupper($xml->floor[$k]->book[$i]->range->end);
         $aisle = $xml->floor[$k]->book[$i]->range->aisle;

         // echo "Book id=$id aisle=$aisle<br>";
         if ($id <= $end && $id >= $start) {
            echo "<response><location>$aisle</location><floor>$floor</floor><error>0</error></response>";
            exit;
         }
      }
   }

   // If we reached here, we couldn't find the book!
   echo "<response><error>1</error><message>Item with ID of " . $_GET['id'] . " not found.</message></response>";
?>

